package com.ideal.manage.esms.service.system;

import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.esms.EsmsUnitCell;
import com.ideal.manage.esms.bean.esms.EsmsUnitCellScanBase;
import com.ideal.manage.esms.bean.project.ProjectManage;
import com.ideal.manage.esms.repository.monitor.UnitCellDataRepository;
import com.ideal.manage.esms.repository.monitor.UnitCellDataScanBaseRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import com.ideal.manage.esms.util.ElasticsearchUtils;
import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author Allen
 */
@Service
public class UnitCellDataScanService {

    @Autowired
    private EquipmentManageRepository equipmentManageRepository;

    @Autowired
    private ProjectManageRepository projectManageRepository;

    @Autowired
    private UnitCellDataScanBaseRepository unitCellDataScanBaseRepository;

    @Autowired
    private UnitCellDataRepository unitCellDataRepository;

    private static final Logger logger = LoggerFactory.getLogger(UnitCellDataScanService.class);

    /**
     * 电池单体每15分钟入库
     *
     * @throws ParseException
     */
    public void getScanBattery() throws ParseException {

        // 定义设备的类型(电池单体)
        String equipmentType = "4";
        // 查询所有项目ip
        List<ProjectManage> projectManages = projectManageRepository.findByAllIp();
        ArrayList<String> ips = new ArrayList<>();
        projectManages.forEach(ProjectManage -> ips.add(ProjectManage.getIp()));
        // 查询15分钟前的es数据库
        LocalDateTime now = LocalDateTime.now();
        long lastDate = now.minusMinutes(15).toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long nowDate = now.toInstant(ZoneOffset.of("+8")).toEpochMilli();

        ArrayList<SearchHit[]> battery = ElasticsearchUtils.getBattery(ips, lastDate, nowDate);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("电池单体扫描" + ":" + " 结束时间" + formatter.format(new Date(nowDate)) + "========" + " 开始时间 " + formatter.format(new Date(lastDate)));
        // 电流
        String batCurrent = "0.0";
        // 数据
        for (int i = 0; i < battery.size(); i++) {
            String ip = ips.get(i);
            // 查询项目下的所有code
            List<String> codes = equipmentManageRepository.findByGroupBattery(equipmentType, ip);
            SearchHit[] hits = battery.get(i);
            for (SearchHit sehit : hits) {
                Map<String, Object> map = sehit.getSourceAsMap();
                if (map.get("BatCurrent") != null) {
                    batCurrent = map.get("BatCurrent").toString();
                }
                for (int j = 0; j < codes.size(); j++) {
                    if (codes.size() < 1) {
                        continue;
                    }
                    String cell = codes.get(j).substring(codes.get(j).indexOf("#") + 1, codes.get(j).length());
                    String code = cell + "Volt";

                    if (map.containsKey(code) && map.containsValue(ip)) {
                        EsmsUnitCellScanBase scan = new EsmsUnitCellScanBase();
                        scan.setCellName(code);
                        scan.setVal(Float.valueOf(map.get(code).toString()));
                        scan.setMacid(map.get("macid").toString());
                        scan.setCreateTime(new Date());
                        scan.setDateTime(formatter.parse(map.get("date_time").toString()));
                        scan.setProjectIp(ip);
                        scan.setBatcrrentVal(Float.valueOf(batCurrent));
                        unitCellDataScanBaseRepository.save(scan);
                    }
                }
            }
        }
        setBatteryData(lastDate, nowDate);
        System.out.println("电池单体过滤完成");
    }

    /**
     * 入库15分钟的数据
     */
    public void setBatteryData(Long lastDate, Long nowDate) throws ParseException {
        String equipmentType = "4";
        // 查询所有项目ip
        List<ProjectManage> projectManages = projectManageRepository.findByAllIp();
        ArrayList<String> ips = new ArrayList<>();
        projectManages.forEach(ProjectManage -> ips.add(ProjectManage.getIp()));
        for (int i = 0; i < ips.size(); i++) {
            String ip = ips.get(i);
            //获取项目级的所有code
            List<String> codes = equipmentManageRepository.findByGroupBattery(equipmentType, ip);

            for (int j = 0; j < codes.size(); j++) {
                if (codes.get(j).length() < 9) {
                    return;
                }
                String cell = codes.get(j).substring(codes.get(j).indexOf("#") + 1, codes.get(j).length());
                String code = cell + "Volt";
                // 过滤数据得到 平均值,最大,最小..
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date end = simpleDateFormat.parse(simpleDateFormat.format(nowDate));
                Date strat = simpleDateFormat.parse(simpleDateFormat.format(lastDate));

                List<EsmsUnitCellScanBase> datas = unitCellDataScanBaseRepository.findCodeByData(code, strat, end);

                if (datas.size() != 0) {
                    Float sum = 0.0f;
                    Float batcurrent = 0.0f;
                    ArrayList<Float> vals = new ArrayList<>();
                    for (EsmsUnitCellScanBase ecs : datas) {
                        sum += ecs.getVal();
                        vals.add(ecs.getVal());
                        batcurrent = ecs.getBatcrrentVal();
                    }

                    EsmsUnitCell unitCell = new EsmsUnitCell();
                    unitCell.setCellName(datas.get(0).getCellName());
                    unitCell.setMacid(datas.get(0).getMacid());
                    unitCell.setAvgVal(sum / vals.size());
                    unitCell.setMaxVal(Collections.max(vals));
                    unitCell.setMinVal(Collections.min(vals));
                    unitCell.setCreateTime(new Date());
                    unitCell.setDateTime(datas.get(0).getDateTime());
                    unitCell.setProjectIp(ip);
                    unitCell.setBatcrrentVal(batcurrent);

                    unitCellDataRepository.save(unitCell);
                }
            }
        }
    }
/*****************************************************电池模组 , 电池单体*************************************************/
    /**
     * 电池单体数据
     *
     * @param code
     * @param esName
     * @param ip
     * @param freque
     * @param startTime
     * @param endTime
     * @param value_type
     * @return
     * @throws ParseException
     */

    public JSONObject getScanBatteryData(String code, String esName, String ip, String freque, Long startTime, Long endTime, String value_type) throws ParseException {
        //获取macid esname
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String macid = code.substring(0, code.indexOf("#"));
        String esname;
        if ("BatCurrent".equals(esName)) {
            esname = code.substring(code.indexOf("#") + 1, code.length()) + "Volt";
        } else {
            esname = code.substring(code.indexOf("#") + 1, code.length()) + esName;
        }
        // 获取时间范围
        List timeRange = getTimeRange(freque, startTime, endTime);
        // 时间段格式化 格式
        String format = timeRange.get(0).toString();
        // 间隔时间
        Long time = Long.valueOf(timeRange.get(1).toString());
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) timeRange.get(2);

        Date start = formatter.parse(formatter.format(new Date(startTime)));
        Date end = formatter.parse(formatter.format(new Date(endTime)));

        Map<Long, Float> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        switch (value_type) {
            //最小值
            case "min":
                List<EsmsUnitCell> minDatas = unitCellDataRepository.findByCellData(macid, esname, start, end, ip);
                for (EsmsUnitCell esCell : minDatas) {
                    if ("BatCurrent".equals(esName)) {
                        if (esCell.getBatcrrentVal() == null) {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                    0.0F);
                        } else {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                    Float.valueOf(esCell.getBatcrrentVal()));
                        }
                    } else {
                        map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                Float.valueOf(esCell.getMinVal()) * 0.001F);
                    }


                }


                break;
            case "max":
                //最大值
                List<EsmsUnitCell> maxDatas = unitCellDataRepository.findByCellData(macid, esname, start, end, ip);
                for (EsmsUnitCell esCell : maxDatas) {
                    if ("BatCurrent".equals(esName)) {
                        if (esCell.getBatcrrentVal() == null) {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                    0.0F);
                        } else {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                    Float.valueOf(esCell.getBatcrrentVal()));
                        }
                    } else {
                        map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                Float.valueOf(esCell.getMaxVal()) * 0.001F);
                    }

                }

                break;
            case "avg":
                //平均值
                List<EsmsUnitCell> avgDatas = unitCellDataRepository.findByCellData(macid, esname, start, end, ip);
                for (EsmsUnitCell esCell : avgDatas) {
                    if ("BatCurrent".equals(esName)) {
                        if (esCell.getBatcrrentVal() == null) {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(), 0.0F);
                        } else {
                            map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                    Float.valueOf(esCell.getBatcrrentVal()));
                        }
                    } else {
                        map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                                Float.valueOf(esCell.getAvgVal()) * 0.001F);
                    }

                }

                break;
        }

        return getformatData(startTime, endTime, time, format, freque, map, jsonObject, simpleDateFormat);


    }

    /**
     * 电池单体数据
     *
     * @param code
     * @param esName
     * @param ip
     * @param freque
     * @param startTime
     * @param endTime
     * @param value_type
     * @return
     * @throws ParseException
     */

    public Map getMinAndMax(String code, String esName, String ip, String freque, Long startTime, Long endTime, String value_type) throws ParseException {
        //获取macid esname
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String macid = code.substring(0, code.indexOf("#"));
        String esname;
        if ("BatCurrent".equals(esName)) {
            esname = code.substring(code.indexOf("#") + 1, code.length()) + "Volt";
        } else {
            esname = code.substring(code.indexOf("#") + 1, code.length()) + esName;
        }
        // 获取时间范围
        List timeRange = getTimeRange(freque, startTime, endTime);
        // 时间段格式化 格式
        String format = timeRange.get(0).toString();
        // 间隔时间
        Long time = Long.valueOf(timeRange.get(1).toString());
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) timeRange.get(2);

        Date start = formatter.parse(formatter.format(new Date(startTime)));
        Date end = formatter.parse(formatter.format(new Date(endTime)));

        Map<Long, Float> map = new HashMap<>();
        Map<Long, Float> minMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        JSONObject minJsonObject = new JSONObject();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<EsmsUnitCell> diff = unitCellDataRepository.findByCellData(macid, esname, start, end, ip);
        for (EsmsUnitCell esCell : diff) {
            if ("BatCurrent".equals(esName)) {
                if (esCell.getBatcrrentVal() == null) {
                    map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                            Float.valueOf(0.0F));
                } else {
                    map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                            Float.valueOf(esCell.getBatcrrentVal()));
                }
            } else {
                // 极值
                map.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                        Float.valueOf(esCell.getMinVal()) * 0.001F);
                // 极差
                minMap.put(sdf.parse(sdf.format(esCell.getDateTime())).getTime(),
                        Float.valueOf(esCell.getMaxVal() - esCell.getMinVal()) * 0.001F);
            }
        }
        return getMinAndMaxValue(startTime, endTime, time, format, freque, map, minMap, jsonObject, minJsonObject, simpleDateFormat);

    }

    /**
     * 返回数据
     *
     * @param startTime
     * @param time
     * @param format
     * @param time_type
     * @param map
     * @param jsonObject
     * @return
     */

    private JSONObject getformatData(Long startTime, Long endTime, Long time, String format,
                                     String time_type, Map<Long, Float> map, JSONObject jsonObject,
                                     SimpleDateFormat simpleDateFormat) throws ParseException {
        List<Float> val = new ArrayList<>();
        Float value = 0.0F;
        String name = "";
        int k = 0;
        switch (time_type) {
            case "hour":
                k = 24;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        long dataTime = simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime();
                        if (startTime + time * j == dataTime) {
                            name = new SimpleDateFormat(format).format(new Date(dataTime));
                            value = entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));

                        }
                    }

                    jsonObject.put(name, value);
                    value = 0.0F;
                }
                break;
            case "day":
                SimpleDateFormat simpleDateFormatt = new SimpleDateFormat("yyyy-MM-dd");
                long lastTime = simpleDateFormatt.parse(simpleDateFormatt.format(new Date(endTime))).getTime();
                long l = (lastTime - startTime) / (time);
                k = (int) l + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value = entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    value = 0.0F;
                }

                break;
            case "month":
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                long monthTime = sdf.parse(sdf.format(new Date(endTime))).getTime();
                long ti = (monthTime - startTime);
                Float o = Float.valueOf(ti) / Float.valueOf(time);
                k = (int) Math.rint(o) + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value = entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);

                    value = 0.0F;
                }
                break;
            case "15":
                SimpleDateFormat sidf = new SimpleDateFormat("yyyy-MM-dd HH");
                long fiveM = sidf.parse(sidf.format(new Date(endTime))).getTime();
                long fives = fiveM - startTime;
                Float v = Float.valueOf(fives) / Float.valueOf(time);
                k = (int) Math.rint(v) + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value += entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }

                    jsonObject.put(name, value);
                    value = 0.0F;
                }
                break;
        }


        return jsonObject;
    }

    /**
     * 返回数据
     *
     * @param startTime
     * @param time
     * @param format
     * @param time_type
     * @param map
     * @param jsonObject
     * @return
     */

    private Map getMinAndMaxValue(Long startTime, Long endTime, Long time, String format,
                                  String time_type, Map<Long, Float> map, Map<Long, Float> minMap, JSONObject jsonObject, JSONObject minjsonObject,
                                  SimpleDateFormat simpleDateFormat) throws ParseException {

        Float value = 0.0F;
        String name = "";
        String minName = "";
        Float minValue = 0.0F;
        int k = 0;
        switch (time_type) {
            case "hour":
                k = 24;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        long dataTime = simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime();
                        if (startTime + time * j == dataTime) {
                            name = new SimpleDateFormat(format).format(new Date(dataTime));
                            value = entry.getValue();
                            jsonObject.put(name, value);
                            break;
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));

                        }
                    }
                    for (Map.Entry<Long, Float> entry : minMap.entrySet()) {
                        long dataTime = simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime();
                        if (startTime + time * j == dataTime) {
                            minName = new SimpleDateFormat(format).format(new Date(dataTime));
                            minValue = entry.getValue();
                            minjsonObject.put(minName, minValue);
                            break;
                        } else {
                            minName = new SimpleDateFormat(format).format(new Date(startTime + time * j));

                        }
                    }

                    jsonObject.put(name, value);
                    minjsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                }
                break;
            case "day":
                SimpleDateFormat simpleDateFormatt = new SimpleDateFormat("yyyy-MM-dd");
                long lastTime = simpleDateFormatt.parse(simpleDateFormatt.format(new Date(endTime))).getTime();
                long l = (lastTime - startTime) / (time);
                k = (int) l + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value = entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    for (Map.Entry<Long, Float> entry : minMap.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            minName = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            minValue = entry.getValue();
                        } else {
                            minName = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    minjsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                }

                break;
            case "month":
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                long monthTime = sdf.parse(sdf.format(new Date(endTime))).getTime();
                long ti = (monthTime - startTime);
                Float o = Float.valueOf(ti) / Float.valueOf(time);
                k = (int) Math.rint(o) + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value = entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    for (Map.Entry<Long, Float> entry : minMap.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            minName = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            minValue = entry.getValue();
                        } else {
                            minName = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    minjsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                }
                break;
            case "15":
                SimpleDateFormat sidf = new SimpleDateFormat("yyyy-MM-dd HH");
                long fiveM = sidf.parse(sidf.format(new Date(endTime))).getTime();
                long fives = fiveM - startTime;
                Float v = Float.valueOf(fives) / Float.valueOf(time);
                k = (int) Math.rint(v) + 1;
                for (int j = 0; j < k; j++) {
                    for (Map.Entry<Long, Float> entry : map.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            value += entry.getValue();
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    for (Map.Entry<Long, Float> entry : minMap.entrySet()) {
                        if ((entry.getKey() > startTime + time * j) && (entry.getKey() < startTime + time * (j + 1))) {
                            minName = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(entry.getKey())).getTime()));
                            minValue += entry.getValue();
                        } else {
                            minName = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    minjsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                }
                break;
        }
        Map result = new HashMap();
        result.put("jsonObject", jsonObject);
        result.put("minjsonObject", minjsonObject);
        return result;

    }


    /**
     * 格式化时间范围
     *
     * @param time_type
     * @param startTime
     * @param endTime
     * @return
     */
    public List getTimeRange(String time_type, Long startTime, Long endTime) {
        Long time;
        String format = "HH:mm";
        SimpleDateFormat simpleDateFormat = null;
        // 3. 时间类型
        switch (time_type) {
            case "hour":
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                // 设置间隔时间
                time = 1000L * 60L * 60L;
                if ((endTime - startTime) > 1000 * 60 * 60 * 24) {
                    format = "MM-dd HH:mm";
                } else {
                    format = "HH:mm";
                }
                break;
            case "day":
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                time = 1000L * 60L * 60L * 24L;
                format = "MM-dd";
                break;
            case "month":
                simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                time = 1000L * 60L * 60L * 24L * 30L;
                format = "yyyy-MM";
                break;
            case "15":
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
                time = 1000L * 60L * 15L;
                format = "HH:mm";
                break;
            default:
                return null;
        }
        List<Object> objects = new ArrayList<>();
        objects.add(format);
        objects.add(time);
        objects.add(simpleDateFormat);
        return objects;
    }

    /**
     * 电池模组历史曲线
     *
     * @param codes      电池模组下的所有的电池单体
     * @param macid      唯一标识
     * @param ip
     * @param freque     时间范围
     * @param startTime
     * @param endTime
     * @param value_type
     * @return
     * @throws ParseException
     */
    public JSONObject getScanGroupBatteryData(List<String> codes, String esName, String macid, String ip, String freque, Long startTime, Long endTime, String value_type) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取时间范围
        List timeRange = getTimeRange(freque, startTime, endTime);
        // 时间段格式化 格式
        String format = timeRange.get(0).toString();
        // 间隔时间
        Long time = Long.valueOf(timeRange.get(1).toString());
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) timeRange.get(2);

        Date start = formatter.parse(formatter.format(new Date(startTime)));
        Date end = formatter.parse(formatter.format(new Date(endTime)));
        // 获取选中的电池模组下的所有的电池单体的数据


        JSONObject jsonObject = new JSONObject();

        List<EsmsUnitCell> Datas = null;
        switch (value_type) {
            //最小值
            case "min":
                Datas = unitCellDataRepository.findByGroupCellData(codes, macid, start, end, ip);

                break;
            case "max":
                //最大值
                Datas = unitCellDataRepository.findByGroupCellData(codes, macid, start, end, ip);

                break;
            case "avg":
                //平均值
                Datas = unitCellDataRepository.findByGroupCellData(codes, macid, start, end, ip);

                break;
        }
        return getformatGroupData(startTime, endTime, time, format, freque, Datas, jsonObject, simpleDateFormat,value_type,esName);
    }

    /**
     * 电池模组 历史曲线
     *
     * @param startTime
     * @param endTime
     * @param time
     * @param format
     * @param time_type
     * @param datas
     * @param jsonObject
     * @param simpleDateFormat
     * @return
     */
    private JSONObject getformatGroupData(Long startTime, Long endTime, Long time,
                                          String format, String time_type, List<EsmsUnitCell> datas,
                                          JSONObject jsonObject, SimpleDateFormat simpleDateFormat,String type,String esName) throws ParseException {
        List<String> val = new ArrayList<>();
        Float value = 0.0F;
        String name = "";
        int k = 0;
        switch (time_type) {
            case "hour":
                k = 24;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : datas) {
                        long dataTime = simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime();
                        if (startTime + time * j == dataTime) {
                            name = new SimpleDateFormat(format).format(new Date(dataTime));

                            if ("BatCurrent".equals(esName)) {
                                if (esUn.getBatcrrentVal() == null) {
                                    value = 0.0F;
                                } else {
                                    value = esUn.getBatcrrentVal();
                                }
                            }

                            if (val.contains(esUn.getCellName())) {
                                continue;
                            }
                            val.add(esUn.getCellName());
                            if(type.equals("avg")){
                                value += esUn.getAvgVal() * 0.001F;
                            }else if(type.equals("min")){
                                value += esUn.getMinVal() * 0.001F;
                            }else {
                                value += esUn.getMaxVal() * 0.001F;
                            }
                            if ("BatCurrent".equals(esName)) {
                                if (esUn.getBatcrrentVal() == null) {
                                    value = 0.0F;
                                } else {
                                    value = esUn.getBatcrrentVal();
                                }
                            }

                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));

                        }
                    }

                    jsonObject.put(name, value);
                    value = 0.0F;
                    val.clear();
                }
                break;
            case "day":
                SimpleDateFormat simpleDateFormatt = new SimpleDateFormat("yyyy-MM-dd");
                long lastTime = simpleDateFormatt.parse(simpleDateFormatt.format(new Date(endTime))).getTime();
                long l = (lastTime - startTime) / (time);
                k = (int) l + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : datas) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));

                            if ("BatCurrent".equals(esName)) {
                                if (esUn.getBatcrrentVal() == null) {
                                    value = 0.0F;
                                } else {
                                    value = esUn.getBatcrrentVal();
                                }
                            }
                            if (val.contains(esUn.getCellName())) {
                                continue;
                            }
                            val.add(esUn.getCellName());
                            if(type.equals("avg")){
                                value += esUn.getAvgVal() * 0.001F;
                            }else if(type.equals("min")){
                                value += esUn.getMinVal() * 0.001F;
                            }else {
                                value += esUn.getMaxVal() * 0.001F;
                            }

                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    value = 0.0F;
                    val.clear();
                }

                break;
            case "month":
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                long monthTime = sdf.parse(sdf.format(new Date(endTime))).getTime();
                long ti = (monthTime - startTime);
                Float o = Float.valueOf(ti) / Float.valueOf(time);
                k = (int) Math.rint(o) + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : datas) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            if ("BatCurrent".equals(esName)) {
                                if (esUn.getBatcrrentVal() == null) {
                                    value = 0.0F;
                                } else {
                                    value = esUn.getBatcrrentVal();
                                }
                            }
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));
                            if (val.contains(esUn.getCellName())) {
                                continue;
                            }
                            val.add(esUn.getCellName());
                            if(type.equals("avg")){
                                value += esUn.getAvgVal() * 0.001F;
                            }else if(type.equals("min")){
                                value += esUn.getMinVal() * 0.001F;
                            }else {
                                value += esUn.getMaxVal() * 0.001F;
                            }

                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }
                    jsonObject.put(name, value);
                    value = 0.0F;
                    val.clear();
                }
                break;
            case "15":
                SimpleDateFormat sidf = new SimpleDateFormat("yyyy-MM-dd HH");
                long fiveM = sidf.parse(sidf.format(new Date(endTime))).getTime();
                long fives = fiveM - startTime;
                Float v = Float.valueOf(fives) / Float.valueOf(time);
                k = (int) Math.rint(v) + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : datas) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));
                            if ("BatCurrent".equals(esName)) {
                                if (esUn.getBatcrrentVal() == null) {
                                    value = 0.0F;
                                } else {
                                    value = esUn.getBatcrrentVal();
                                }
                            }
                            if (val.contains(esUn.getCellName())) {
                                continue;
                            }
                            val.add(esUn.getCellName());
                            if(type.equals("avg")){
                                value += esUn.getAvgVal() * 0.001F;
                            }else if(type.equals("min")){
                                value += esUn.getMinVal() * 0.001F;
                            }else {
                                value += esUn.getMaxVal() * 0.001F;
                            }

                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }

                    jsonObject.put(name, value);
                    value = 0.0F;
                    val.clear();
                }
                break;
        }


        return jsonObject;
    }

    /**
     * 电池模组历史曲线极值极差
     *
     * @param codes
     * @param esName
     * @param ip
     * @param freque
     * @param startTime
     * @param endTime
     * @param min
     * @return
     * @throws ParseException
     */
    public Map getGroupBatteryMinAndMax(List<String> codes, String esName, String macid, String ip, String freque, Long startTime, Long endTime, String min) throws ParseException {
        //获取macid esname
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      ;

        // 获取时间范围
        List timeRange = getTimeRange(freque, startTime, endTime);
        // 时间段格式化 格式
        String format = timeRange.get(0).toString();
        // 间隔时间
        Long time = Long.valueOf(timeRange.get(1).toString());
        SimpleDateFormat simpleDateFormat = (SimpleDateFormat) timeRange.get(2);

        Date start = formatter.parse(formatter.format(new Date(startTime)));
        Date end = formatter.parse(formatter.format(new Date(endTime)));


        JSONObject jsonObject = new JSONObject();
        JSONObject minJsonObject = new JSONObject();


        List<EsmsUnitCell> diff = unitCellDataRepository.findByGroupCellData(codes, macid, start, end, ip);

        return getGroupMinAndMaxValue(startTime, endTime, time, format, freque,  jsonObject, minJsonObject, simpleDateFormat,diff);

    }

    /**
     * 电池模组极值极差
     * @param startTime
     * @param endTime
     * @param time
     * @param format
     * @param time_type
     * @param jsonObject
     * @param minJsonObject
     * @param simpleDateFormat
     * @param diff
     * @return
     * @throws ParseException
     */
    private Map getGroupMinAndMaxValue(Long startTime, Long endTime, Long time,
                                       String format, String time_type,
                                       JSONObject jsonObject, JSONObject minJsonObject,
                                       SimpleDateFormat simpleDateFormat, List<EsmsUnitCell> diff) throws ParseException {
        List<Float> cellName  = new ArrayList<>();
        Float value = 0.0F;
        String name = "";
        String minName = "";
        Float minValue = 0.0F;
        int k = 0;
        switch (time_type) {
            case "hour":
                k = 24;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : diff) {
                        long dataTime = simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime();
                        if (startTime + time * j == dataTime) {

                            cellName.add(esUn.getMinVal() * 0.001F);
                            name = new SimpleDateFormat(format).format(new Date(dataTime));
                            value = Collections.min(cellName);

                            minName  = name;
                            minValue = (esUn.getMaxVal() * 0.001F) - (esUn.getMinVal()* 0.001F);
                            break;
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));

                        }
                    }

                    jsonObject.put(name, value);
                    minJsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                    cellName.clear();
                }
                break;
            case "day":
                SimpleDateFormat simpleDateFormatt = new SimpleDateFormat("yyyy-MM-dd");
                long lastTime = simpleDateFormatt.parse(simpleDateFormatt.format(new Date(endTime))).getTime();
                long l = (lastTime - startTime) / (time);
                k = (int) l + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : diff) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            cellName.add(esUn.getMinVal() * 0.001F);
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));

                            value = Collections.min(cellName);

                            minName  = name;
                            minValue = (esUn.getMaxVal() * 0.001F) - (esUn.getMinVal()* 0.001F);
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }

                    jsonObject.put(name, value);
                    minJsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                    cellName.clear();

                }

                break;
            case "month":
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                long monthTime = sdf.parse(sdf.format(new Date(endTime))).getTime();
                long ti = (monthTime - startTime);
                Float o = Float.valueOf(ti) / Float.valueOf(time);
                k = (int) Math.rint(o) + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : diff) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            cellName.add(esUn.getMinVal() * 0.001F);
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));
                            value = Collections.min(cellName);

                            minName  = name;
                            minValue = (esUn.getMaxVal() * 0.001F) - (esUn.getMinVal()* 0.001F);
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }

                    jsonObject.put(name, value);
                    minJsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                    cellName.clear();
                }
                break;
            case "15":
                SimpleDateFormat sidf = new SimpleDateFormat("yyyy-MM-dd HH");
                long fiveM = sidf.parse(sidf.format(new Date(endTime))).getTime();
                long fives = fiveM - startTime;
                Float v = Float.valueOf(fives) / Float.valueOf(time);
                k = (int) Math.rint(v) + 1;
                for (int j = 0; j < k; j++) {
                    for (EsmsUnitCell esUn : diff) {
                        if ((esUn.getDateTime().getTime() > startTime + time * j) && (esUn.getDateTime().getTime() < startTime + time * (j + 1))) {
                            cellName.add(esUn.getMinVal() * 0.001F);
                            name = new SimpleDateFormat(format).format(new Date(simpleDateFormat.parse(simpleDateFormat.format(esUn.getDateTime())).getTime()));
                            value = Collections.min(cellName);

                            minName  = name;
                            minValue = (Collections.max(cellName)) - (value);
                        } else {
                            name = new SimpleDateFormat(format).format(new Date(startTime + time * j));
                        }

                    }


                    jsonObject.put(name, value);
                    minJsonObject.put(minName, minValue);
                    value = 0.0F;
                    minValue = 0.0F;
                    cellName.clear();
                }
                break;
        }
        Map result = new HashMap();
        result.put("jsonObject", jsonObject);
        result.put("minjsonObject", minJsonObject);
        return result;
    }
}
